package com.example.demo;

import com.example.demo.DAO.UserDAO;
import com.example.demo.Entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(urlPatterns = "/UserAddServlet")
public class UserAddServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UserAddServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求字符编码
        request.setCharacterEncoding("UTF-8");
        System.out.println("进入UserAddServlet");

        // 设置请求字符编码，防止中文乱码
        request.setCharacterEncoding("UTF-8");

        try {
            // 1. 从请求中获取表单数据
            String userLogname = request.getParameter("userLogname");
            String userPwd = request.getParameter("userPwd");
            String userRealname = request.getParameter("userRealname");
            String userEmail = request.getParameter("userEmail");
            int userRole =(request.getParameter("userRole") == null) ? 3 : Integer.parseInt(request.getParameter("userRole"));

            int userState = (request.getParameter("userState") == null) ? 1: Integer.parseInt(request.getParameter("userRole"));

            //创建User对象
            //这里写你自己的构造方法
            User user = User.builder().userLogname(userLogname).userPwd(userPwd).userRealname(userRealname).
                    userEmail(userEmail).userRole(userRole).userState(userState).build();
            //保存到DAO
            UserDAO userDAO = new UserDAO();
            boolean success = userDAO.save(user);
            //重定向
            if(success){
                //这里重定向到资源包处,所以要有getContextPath
                String path =request.getContextPath() + "/manage/userList.html" ;
                System.out.println(path);
                response.sendRedirect(path);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("获取表单数据失败");
            request.setAttribute("error", "获取表单数据失败");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
}

